package org.example.controller;

import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.example.common.Result;
import org.example.config.JwtConfig;
import org.example.model.request.UserRequest;
import org.example.model.request.WechatLoginRequest;
import org.example.model.response.WechatLoginResponse;
import org.example.model.WechatUserInfo;
import org.example.service.WechatService;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.springframework.web.bind.annotation.*;

import java.util.Date;

@RestController
@RequestMapping("/api")
@CrossOrigin(origins = "*") // 允许跨域请求
@Tag(name = "微信登录接口")
public class WechatLoginController {

    private final WechatService wechatService;
//    private final String jwtSecret = "your_jwt_secret"; // 生成JWT的密钥，一般使用环境变量或配置文件管理
    private final JwtConfig jwtConfig; // 使用 JwtConfig


    public WechatLoginController(WechatService wechatService, JwtConfig jwtConfig) {
        this.wechatService = wechatService;
        this.jwtConfig = jwtConfig;
    }


    /**
     * 微信一键登录
     * @param request
     * @return
     */
    @Operation(summary = "微信一键登录")
    @PostMapping("/login/wechat")
    public Result<WechatLoginResponse> login(@RequestBody WechatLoginRequest request)  {
        // 根据code获取该用户信息
        WechatUserInfo wechatUserInfo = wechatService.wxLogin(request.getCode());
        // 生成JWT令牌--->长Token
        String token = Jwts.builder()
                .setSubject(wechatUserInfo.getOpenid())
                .setIssuedAt(new Date())
                .setExpiration(new Date(System.currentTimeMillis() + 86400000)) // 24小时过期
                .signWith(SignatureAlgorithm.HS512, jwtConfig.getJwtSecret())
                .compact();

        // 生成JWT令牌--->短Token
        String temporaryToken = Jwts.builder()
                .setSubject(wechatUserInfo.getOpenid())
                .setIssuedAt(new Date())
                .setExpiration(new Date(System.currentTimeMillis() + 600)) // 10分钟过期
                .signWith(SignatureAlgorithm.HS512, jwtConfig.getJwtSecret())
                .compact();

        // 构建响应
        WechatLoginResponse response = WechatLoginResponse.builder()
                .uid(String.valueOf(wechatUserInfo.getId() + 100100))
                .token(token)
                .temporaryToken(temporaryToken)
                .build();

        return Result.success(response);
    }

    @PostMapping("/UserInfo")
    public void userInfo(@RequestBody UserRequest userRequest) {
        wechatService.setUserInfo(userRequest);
    }

}
